package com.ssy.lingxi.member.merchant.repository;

import com.ssy.lingxi.member.merchant.entity.MemberTradeCommentHistoryDO;
import com.ssy.lingxi.member.merchant.model.dto.CommentSummaryDTO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 会员交易评论历史记录操作Repository
 * @author 万宁
 * @version 2.0.0
 * @date 2020-07-16
 */
@Repository
public interface MemberTradeCommentHistoryRepository extends JpaRepository<MemberTradeCommentHistoryDO, Long>, JpaSpecificationExecutor<MemberTradeCommentHistoryDO> {

    List<MemberTradeCommentHistoryDO> findAllByOrderIdAndTradeType(Long orderId, Integer tradeType);

    List<MemberTradeCommentHistoryDO> findAllBySubMemberIdAndSubRoleId(Long subMemberId, Long subRoleId);

    Page<MemberTradeCommentHistoryDO> findAllByMemberIdAndRoleId(Long memberId, Long roleId, Pageable pageable);

    Integer countByMemberIdAndRoleId(Long memberId, Long roleId);

    Integer countBySubMemberIdAndSubRoleId(Long memberId, Long roleId);

    List<MemberTradeCommentHistoryDO> findAllByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(Long upperMemberId, Long upperRoleId, Long subMemberId, Long subRoleId);

    List<MemberTradeCommentHistoryDO> findAllByMemberIdAndRoleIdAndOrderId(Long memberId, Long roleId, Long orderId);

    @Transactional
    void deleteAllBySubMemberIdAndSubRoleId(Long subMemberId, Long subRoleId);

    @Transactional
    void deleteByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(Long memberId, Long roleId, Long subMemberId, Long subRoleId);

    @Transactional
    void deleteAllByIdIn(List<Long> ids);

    @Query(value = "select new com.ssy.lingxi.member.merchant.model.dto.CommentSummaryDTO(count(mth.id), sum(case when (mth.star = 5 or mth.star = 4) then 1 else 0 end), sum(case when mth.star=3 then 1 else 0 end), sum(case when (mth.star = 2 or mth.star=1) then 1 else 0 end)) from MemberTradeCommentHistoryDO mth where mth.memberId = :memberId and mth.roleId = :roleId and mth.subMemberId = :subMemberId and mth.subRoleId = :subRoleId group by mth.memberId, mth.roleId, mth.subMemberId, mth.subRoleId")
    CommentSummaryDTO groupByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(Long memberId, Long roleId, Long subMemberId, Long subRoleId);
}
